<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true"
             label-width="68px">
      <el-form-item label="日期" prop="beginDate">
        <el-date-picker v-model="queryParams.beginDate" value-format="YYYY-MM-DD HH:mm:ss"
                        type="daterange"
                        start-placeholder="开始日期" end-placeholder="结束日期"
                        :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                        class="!w-240px" @change="handleQuery"/>
      </el-form-item>
      <el-form-item label="账号" prop="orgId">
        <el-select v-model="queryParams.orgId" clearable class="!w-140px" @change="handleQuery">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.ASA_ORG_ID)" :key="dict.value"
                     :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="应用" prop="appleIdentifier">
        <el-select v-model="queryParams.appleIdentifier" placeholder="请选择应用" clearable
                   class="!w-140px" @change="handleQuery">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.ASA_APP_ID)" :key="dict.value"
                     :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="国家" prop="countryCode">
        <el-input v-model="queryParams.countryCode" placeholder="请输入国家" clearable
                  @keyup.enter="handleQuery" class="!w-140px" @change="handleQuery"/>
      </el-form-item>
      <el-form-item label="数据类型" prop="dataType">
        <el-select v-model="queryParams.dataType" clearable class="!w-120px"
                   @change="handleQuery">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.ASC_DATA_TYPE)" :key="dict.value"
                     :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="订阅类型" prop="subscription">
        <el-select v-model="queryParams.subscription" clearable
                   class="!w-120px" @change="handleQuery">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.ASC_SUB_TYPE)" :key="dict.value"
                     :label="dict.label" :value="dict.label"/>
        </el-select>
      </el-form-item>
      <el-form-item label="产品标识" prop="productTypeIdentifier">
        <el-select v-model="queryParams.productTypeIdentifier" clearable
                   class="!w-120px" @change="handleQuery">
          <el-option v-for="dict in getDictOptions(DICT_TYPE.ASC_PRODUCT_TYPE_IDENTITY)"
                     :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['ascsc:sales-report:export']">
          <Icon icon="ep:download" class="mr-5px"/>
          导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table class="responsive-table" v-loading="loading" :data="list" :stripe="true"
              :show-overflow-tooltip="true" show-summary :summary-method="getSummaries">
      <el-table-column label="日期" align="center" prop="beginDate" :formatter="dateFormatter3"
                       :min-width="100" sortable/>
      <el-table-column label="账号" align="center" prop="orgId" :min-width="85" sortable>
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ASA_ORG_ID" :value="scope.row.orgId"/>
        </template>
      </el-table-column>
      <el-table-column label="产品" align="center" prop="appleIdentifier" :min-width="100" sortable>
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ASA_APP_ID" :value="scope.row.appleIdentifier"/>
        </template>
      </el-table-column>
      <el-table-column label="国家" align="center" prop="countryCode" :formatter="formatCountryCode"
                       :min-width="100" sortable/>
      <!--      <el-table-column label="产品名称" align="center" prop="title" :min-width="140"/>-->
      <el-table-column label="数量" align="center" prop="units" sortable/>
      <el-table-column label="销售总额USD" align="center" prop="customerPriceUsd"
                       :formatter="usdFormatter" sortable/>
      <el-table-column label="订阅收入总额USD" align="center" prop="developerProceedsUsd"
                       :formatter="usdFormatter" sortable/>
      <el-table-column label="原币销售单价" align="center" prop="customerPrice" sortable/>
      <el-table-column label="原币收入单价" align="center" prop="developerProceeds" sortable/>
      <el-table-column label="原币收入单价" align="center" prop="developerProceeds" sortable/>
      <el-table-column label="原币收入单价" align="center" prop="developerProceeds" sortable/>
      <el-table-column label="货币" align="center" prop="customerCurrency" sortable/>
      <el-table-column label="产品标识" align="center" prop="productTypeIdentifier" sortable/>
      <el-table-column label="订阅类型" align="center" prop="subscription" sortable/>
      <el-table-column label="订阅周期" align="center" prop="period" sortable/>
      <!--      <el-table-column label="推广码" align="center" prop="promoCode"/>-->
      <!--      <el-table-column label="父应用" align="center" prop="parentIdentifier" />-->
      <el-table-column label="App版本" align="center" prop="version" sortable/>
      <el-table-column label="创建时间" :formatter="dateFormatter" align="center" prop="createTime"
                       sortable :min-width="120"/>
      <!--      <el-table-column label="提供者" align="center" prop="provider" />
      <el-table-column label="应用发布国家" align="center" prop="providerCountry" />
      <el-table-column label="开发者" align="center" prop="developer" />
      <el-table-column label="结束日期" align="center" prop="endDate" />
      <el-table-column label="货币符号" align="center" prop="customerCurrency" />
      <el-table-column label="分类" align="center" prop="category" />
      <el-table-column label="CMB" align="center" prop="cmb" />
      <el-table-column label="设备类型" align="center" prop="device" />
      <el-table-column label="系统" align="center" prop="supportedPlatforms" />
      <el-table-column label="原因" align="center" prop="proceedsReason" />
      <el-table-column label="退款" align="center" prop="preservedPricing" />
      <el-table-column label="客户端" align="center" prop="client" />
      <el-table-column label="订单类型" align="center" prop="orderType" />-->
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"/>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <SalesReportForm ref="formRef" @success="getList"/>
</template>

<style scoped>
.responsive-table {
  height: 600px;
}

@media (max-width: 768px) and (orientation: portrait) {
  .responsive-table {
    height: 400px;
    /* 移动设备竖屏高度 */
  }
}

@media (max-width: 768px) and (orientation: landscape) {
  .responsive-table {
    height: 300px;
    /* 移动设备横屏高度 */
  }
}
</style>

<script setup lang="ts">
import {dateFormatter, dateFormatter3} from '@/utils/formatTime'
import download from '@/utils/download'
import {SalesReportApi, SalesReportVO} from '@/api/ascsc/salesreport'
import SalesReportForm from './SalesReportForm.vue'
import {DICT_TYPE, getDictOptions, getIntDictOptions} from "@/utils/dict";
import {formatCountryCode} from "@/utils";

// 获取当前日期和过去7天的日期，并格式化为 'yyyy-MM-dd HH:mm:ss'，使用北京时间
const getDefaultDateRange = () => {
  const toBeijingTime = (date) => {
    const offset = date.getTimezoneOffset() * 60000;
    // 28800000ms = 8 hours
    return new Date(date.getTime() + offset + 28800000);
  };

  const formatDateTime = (date) => {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    const h = String(date.getHours()).padStart(2, '0');
    const min = String(date.getMinutes()).padStart(2, '0');
    const s = String(date.getSeconds()).padStart(2, '0');
    return `${y}-${m}-${d} ${h}:${min}:${s}`;
  };

  const endDate = toBeijingTime(new Date());
  const startDate = toBeijingTime(new Date());
  startDate.setDate(startDate.getDate() - 2); // 这里修正为 startDate
  endDate.setDate(endDate.getDate() - 2); // 这里修正为 startDate

  // 设置开始时间为 00:00:00，结束时间为 23:59:59
  startDate.setHours(0, 0, 0, 0);
  endDate.setHours(23, 59, 59, 999);

  console.log(formatDateTime(startDate), formatDateTime(endDate));
  return [formatDateTime(startDate), formatDateTime(endDate)];
};

/** ASA管理系统 列表 */
defineOptions({name: 'SalesReport'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<SalesReportVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 200,
  orgId: undefined,
  provider: undefined,
  providerCountry: undefined,
  sku: undefined,
  developer: undefined,
  title: undefined,
  version: undefined,
  productTypeIdentifier: undefined,
  units: undefined,
  developerProceeds: undefined,
  beginDate: getDefaultDateRange(),
  endDate: [],
  customerCurrency: undefined,
  countryCode: undefined,
  currencyOfProceeds: undefined,
  appleIdentifier: undefined,
  customerPrice: undefined,
  promoCode: undefined,
  parentIdentifier: undefined,
  subscription: undefined,
  period: undefined,
  category: undefined,
  cmb: undefined,
  device: undefined,
  supportedPlatforms: undefined,
  proceedsReason: undefined,
  preservedPricing: undefined,
  client: undefined,
  orderType: undefined,
  createTime: [],
  dataType: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await SalesReportApi.getSalesReportPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await SalesReportApi.deleteSalesReport(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await SalesReportApi.exportSalesReport(queryParams)
    download.excel(data, 'ASA管理系统.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})

/** 美元符号格式化 */
const usdFormatter = (row, column, cellValue) => {
  return `$${cellValue}`
}

/** 汇总方法 */
/** 汇总方法 */
const getSummaries = (param) => {
  const {columns, data} = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '总计'
      return
    }
    const values = data.map(item => Number(item[column.property]))
    if (!values.every(value => isNaN(value))) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
      if (column.property === 'developerProceedsUsd' || column.property === 'customerPriceUsd') {
        sums[index] = `$${sums[index].toFixed(2)}`
      } else if (column.property === 'units') {
        sums[index] = sums[index];
      } else {
        sums[index] = '';
      }
    }
  })
  return sums
}
</script>
